# Create your views here.
import sys
import json
import logging
from django.http import HttpResponse
from django.core.cache import cache
from django.views.decorators.csrf import csrf_exempt
logger = logging.getLogger('logview.debug')

def clearCache(request):
	try:
		logger.info('CLEAR')
		cache.clear()
	except:
		logger.error('Unexpected error: ' + str(sys.exc_info()[0]))
		return HttpResponse('Unknown error' + str(sys.exc_info()[0]), mimetype=None, status=200)
	return HttpResponse('Done')

@csrf_exempt
def post(request):
	try:
		objs = json.loads(request.POST.items().pop()[0])
		logger.info('ADD recieved JSON (' + str(len(objs)) + ' items): ')
		for tuple in objs.items():
			key = str(tuple[0])
			logger.info('Setting key/value: ' + str(tuple))
			if key[:4] == 'keys':
				logger.error('Key contains \"keys\": ' + key)
				return HttpResponse('Key contains \"keys\": ' + key, mimetype=None, status=200)
			if cache.get(key) == None:
				logger.debug('New key: ' + key)
				keys = cache.get('keys')
				if keys == None:
					logger.debug('Init keys')
					cache.set('keys', key)
				else:
					key_list = keys.split(',')
					key_list.append(key)
					logger.debug('Updated key list: ' + ', '.join(map(str, key_list)))
					cache.set('keys', ','.join(map(str, key_list)))
			cache.set(key, tuple[1])
	except:
		logger.error('Unexpected error: ' + str(sys.exc_info()[0]))
		return HttpResponse('Unknown error: ' + str(sys.exc_info()[0]), mimetype=None, status=200)
	return HttpResponse('Done')
	
@csrf_exempt
def postop(request, option):
	try:
		objs = json.loads(request.POST.items().pop()[0])
		opkeys = 'keys'
		opkeys += option
		logger.info('ADD recieved JSON (' +  str(len(objs)) + ' items): ')
		for tuple in objs.items():
			key = str(tuple[0])
			logger.info('Setting key/value: ' + str(tuple))
			if key[:4] == 'keys':
				logger.error('Key contains \"keys\": ' + key)
				return HttpResponse('Key contains \"keys\": ' + key, mimetype=None, status=200)
			c_keys = cache.get('keys')
			logger.debug('keys: ' + str(c_keys))
			c_opkeys = cache.get(opkeys)
			logger.debug('op keys: (' + str(option) + ') : ' + str(c_opkeys))
			if cache.get(key) == None:
				logger.debug('New key: ' + key)
				if c_keys == None:
					logger.debug('Init keys')
					cache.set('keys', key)
				else:
					key_list = c_keys.split(',')
					key_list.append(key)
					logger.debug('Updated key list: ' + ', '.join(map(str, key_list)))
					cache.set('keys', ','.join(map(str, key_list)))
				if c_opkeys == None:
					logger.debug('Init ' + opkeys)
					cache.set(opkeys, key)
				else:
					key_list = c_opkeys.split(',')
					key_list.append(key)
					logger.debug('Updated ' + opkeys + ' list: ' + ', '.join(map(str, key_list)))
					cache.set(opkeys, ','.join(map(str, key_list)))
			elif c_opkeys != None and not (key in c_opkeys.split(',')):
				logger.error('Key already exists: tuple: ' + str(tuple) + ' key list name: ' + opkeys + 'key list: ' + c_opkeys)
				return HttpResponse('Key already exists: tuple: ' + str(tuple) + ' key list name: ' + opkeys + 'key list: ' + c_opkeys, mimetype=None, status=200)
			cache.set(key, tuple[1])
	except:
		logger.error('Unexpected error: ' + str(sys.exc_info()[0]))
		return HttpResponse('Unknown error: ' + str(sys.exc_info()[0]), mimetype=None, status=200)
	return HttpResponse('Done')

@csrf_exempt
def get(request):
	try:
		keys = cache.get('keys')
		key_list = [] if keys==None else keys.split(',')
		logger.info('GET retrieving vals for keys: ' + ', '.join(map(str, key_list)))
		objs = {}
		for key in key_list:
			val = cache.get(key)
			logger.debug('Retrieved tuple: ' + str(key) + ' ' + str(val))
			objs[key] = val
		data = json.dumps(objs).encode('utf-8')
	except:
		logger.error('Unexpected error: ' + str(sys.exc_info()[0]))
		return HttpResponse('Unknown error: ' + str(sys.exc_info()[0]), mimetype=None, status=200)
	return HttpResponse(data, mimetype='application/json')
	
@csrf_exempt
def getop(request, option):
	try:
		objs = {}
		options = []
		if(option == 'ui'):
			options.append('sim')
			options.append('hw')
		elif(option == 'sim'):
			options.append('ui')
			options.append('hw')
		else:
			options.append(option)
		logger.info('GET retrieving vals for keys: ' + ', '.join(map(str, options)))
		for option in options:
			opkeys = 'keys'
			opkeys += option
			keys = cache.get(opkeys)
			logger.info('op keys (' + str(option) + ') : ' + str(keys))
			if keys != None:
				key_list = keys.split(',')
				logger.debug('Retrieving vals for ' + str(opkeys) + ': ' + ', '.join(map(str, key_list)))
				for key in key_list:
					val = cache.get(key)
					logger.debug('Retrieved tuple: ' + str(key) + ' ' + str(val))
					objs[key] = val
		data = json.dumps(objs).encode('utf-8')
	except:
		logger.error('Unexpected error: ' + str(sys.exc_info()[0]))
		return HttpResponse('Unknown error: ' + str(sys.exc_info()[0]), mimetype=None, status=200)
	return HttpResponse(data, mimetype='application/json')
